{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Make sure you already run\n",
    "\n",
    "1. [xlnet-preprocessing.ipynb](xlnet-preprocessing.ipynb)\n",
    "2. [download-preprocess-dataset.ipynb](download-preprocess-dataset.ipynb)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.environ['CUDA_VISIBLE_DEVICES'] = '3'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:516: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_qint8 = np.dtype([(\"qint8\", np.int8, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:517: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_quint8 = np.dtype([(\"quint8\", np.uint8, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:518: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_qint16 = np.dtype([(\"qint16\", np.int16, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:519: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_quint16 = np.dtype([(\"quint16\", np.uint16, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:520: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_qint32 = np.dtype([(\"qint32\", np.int32, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:525: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  np_resource = np.dtype([(\"resource\", np.ubyte, 1)])\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From /home/husein/english-vietnam/model_utils.py:295: The name tf.train.Optimizer is deprecated. Please use tf.compat.v1.train.Optimizer instead.\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:541: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_qint8 = np.dtype([(\"qint8\", np.int8, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:542: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_quint8 = np.dtype([(\"quint8\", np.uint8, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:543: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_qint16 = np.dtype([(\"qint16\", np.int16, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:544: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_quint16 = np.dtype([(\"quint16\", np.uint16, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:545: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_qint32 = np.dtype([(\"qint32\", np.int32, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:550: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  np_resource = np.dtype([(\"resource\", np.ubyte, 1)])\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "from tensor2tensor.utils import beam_search\n",
    "import xlnet\n",
    "import model_utils"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pickle\n",
    "\n",
    "with open('train-test-xlnet.pkl', 'rb') as fopen:\n",
    "    dataset = pickle.load(fopen)\n",
    "    \n",
    "train_X = dataset['train_X']\n",
    "test_X = dataset['test_X']\n",
    "train_input_ids, train_input_masks, train_segment_ids = train_X\n",
    "test_input_ids, test_input_masks, test_segment_ids = test_X\n",
    "train_Y = dataset['train_Y']\n",
    "test_Y = dataset['test_Y']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "    \n",
    "with open('dictionary.json') as fopen:\n",
    "    dictionary = json.load(fopen)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "dictionary_to = dictionary['to']['dictionary']\n",
    "rev_dictionary_to = dictionary['to']['rev_dictionary']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "GO = dictionary_to['GO']\n",
    "PAD = dictionary_to['PAD']\n",
    "EOS = 3\n",
    "UNK = dictionary_to['UNK']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "import sentencepiece as spm\n",
    "from prepro_utils import preprocess_text, encode_ids\n",
    "\n",
    "sp_model = spm.SentencePieceProcessor()\n",
    "sp_model.Load('xlnet_cased_L-12_H-768_A-12/spiece.model')\n",
    "\n",
    "def tokenize_fn(text):\n",
    "    text = preprocess_text(text, lower= False)\n",
    "    return encode_ids(sp_model, text)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From /home/husein/english-vietnam/xlnet.py:63: The name tf.gfile.Open is deprecated. Please use tf.io.gfile.GFile instead.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "kwargs = dict(\n",
    "      is_training=True,\n",
    "      use_tpu=False,\n",
    "      use_bfloat16=False,\n",
    "      dropout=0,\n",
    "      dropatt=0,\n",
    "      init='normal',\n",
    "      init_range=0.1,\n",
    "      init_std=0.02,\n",
    "      clamp_len=-1)\n",
    "\n",
    "xlnet_parameters = xlnet.RunConfig(**kwargs)\n",
    "xlnet_config = xlnet.XLNetConfig(json_path='xlnet_cased_L-12_H-768_A-12/xlnet_config.json')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "MAX_SEQ_LENGTH = 150\n",
    "\n",
    "SEG_ID_A   = 0\n",
    "SEG_ID_B   = 1\n",
    "SEG_ID_CLS = 2\n",
    "SEG_ID_SEP = 3\n",
    "SEG_ID_PAD = 4\n",
    "\n",
    "special_symbols = {\n",
    "    \"<unk>\"  : 0,\n",
    "    \"<s>\"    : 1,\n",
    "    \"</s>\"   : 2,\n",
    "    \"<cls>\"  : 3,\n",
    "    \"<sep>\"  : 4,\n",
    "    \"<pad>\"  : 5,\n",
    "    \"<mask>\" : 6,\n",
    "    \"<eod>\"  : 7,\n",
    "    \"<eop>\"  : 8,\n",
    "}\n",
    "\n",
    "VOCAB_SIZE = 32000\n",
    "UNK_ID = special_symbols[\"<unk>\"]\n",
    "CLS_ID = special_symbols[\"<cls>\"]\n",
    "SEP_ID = special_symbols[\"<sep>\"]\n",
    "MASK_ID = special_symbols[\"<mask>\"]\n",
    "EOD_ID = special_symbols[\"<eod>\"]\n",
    "\n",
    "size_vocab = VOCAB_SIZE"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "83286 8328\n"
     ]
    }
   ],
   "source": [
    "epoch = 20\n",
    "batch_size = 32\n",
    "warmup_proportion = 0.1\n",
    "num_train_steps = int(len(train_Y) / batch_size * epoch)\n",
    "num_warmup_steps = int(num_train_steps * warmup_proportion)\n",
    "print(num_train_steps, num_warmup_steps)\n",
    "\n",
    "training_parameters = dict(\n",
    "      decay_method = 'poly',\n",
    "      train_steps = num_train_steps,\n",
    "      learning_rate = 1e-5,\n",
    "      warmup_steps = num_warmup_steps,\n",
    "      min_lr_ratio = 0.0,\n",
    "      weight_decay = 0.00,\n",
    "      adam_epsilon = 1e-8,\n",
    "      num_core_per_host = 1,\n",
    "      lr_layer_decay_rate = 1,\n",
    "      use_tpu=False,\n",
    "      use_bfloat16=False,\n",
    "      dropout=0.0,\n",
    "      dropatt=0.0,\n",
    "      init='normal',\n",
    "      init_range=0.1,\n",
    "      init_std=0.02,\n",
    "      clip = 1.0,\n",
    "      clamp_len=-1,)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Parameter:\n",
    "    def __init__(self, decay_method, warmup_steps, weight_decay, adam_epsilon, \n",
    "                num_core_per_host, lr_layer_decay_rate, use_tpu, learning_rate, train_steps,\n",
    "                min_lr_ratio, clip, **kwargs):\n",
    "        self.decay_method = decay_method\n",
    "        self.warmup_steps = warmup_steps\n",
    "        self.weight_decay = weight_decay\n",
    "        self.adam_epsilon = adam_epsilon\n",
    "        self.num_core_per_host = num_core_per_host\n",
    "        self.lr_layer_decay_rate = lr_layer_decay_rate\n",
    "        self.use_tpu = use_tpu\n",
    "        self.learning_rate = learning_rate\n",
    "        self.train_steps = train_steps\n",
    "        self.min_lr_ratio = min_lr_ratio\n",
    "        self.clip = clip\n",
    "        \n",
    "training_parameters = Parameter(**training_parameters)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "def pad_second_dim(x, desired_size):\n",
    "    padding = tf.tile([[[0.0]]], tf.stack([tf.shape(x)[0], desired_size - tf.shape(x)[1], tf.shape(x)[2]], 0))\n",
    "    return tf.concat([x, padding], 1)\n",
    "\n",
    "def ln(inputs, epsilon = 1e-8, scope=\"ln\"):\n",
    "    with tf.variable_scope(scope, reuse=tf.AUTO_REUSE):\n",
    "        inputs_shape = inputs.get_shape()\n",
    "        params_shape = inputs_shape[-1:]\n",
    "    \n",
    "        mean, variance = tf.nn.moments(inputs, [-1], keep_dims=True)\n",
    "        beta= tf.get_variable(\"beta\", params_shape, initializer=tf.zeros_initializer())\n",
    "        gamma = tf.get_variable(\"gamma\", params_shape, initializer=tf.ones_initializer())\n",
    "        normalized = (inputs - mean) / ( (variance + epsilon) ** (.5) )\n",
    "        outputs = gamma * normalized + beta\n",
    "        \n",
    "    return outputs\n",
    "\n",
    "def scaled_dot_product_attention(Q, K, V,\n",
    "                                 causality=False, dropout_rate=0.,\n",
    "                                 training=True,\n",
    "                                 scope=\"scaled_dot_product_attention\"):\n",
    "    with tf.variable_scope(scope, reuse=tf.AUTO_REUSE):\n",
    "        d_k = Q.get_shape().as_list()[-1]\n",
    "\n",
    "        outputs = tf.matmul(Q, tf.transpose(K, [0, 2, 1]))  # (N, T_q, T_k)\n",
    "        outputs /= d_k ** 0.5\n",
    "        outputs = mask(outputs, Q, K, type=\"key\")\n",
    "        if causality:\n",
    "            outputs = mask(outputs, type=\"future\")\n",
    "        outputs = tf.nn.softmax(outputs)\n",
    "        attention = tf.transpose(outputs, [0, 2, 1])\n",
    "        #tf.summary.image(\"attention\", tf.expand_dims(attention[:1], -1))\n",
    "        outputs = mask(outputs, Q, K, type=\"query\")\n",
    "        outputs = tf.layers.dropout(outputs, rate=dropout_rate, training=training)\n",
    "        outputs = tf.matmul(outputs, V)\n",
    "    return outputs\n",
    "\n",
    "def mask(inputs, queries=None, keys=None, type=None):\n",
    "    padding_num = -2 ** 32 + 1\n",
    "    if type in (\"k\", \"key\", \"keys\"):\n",
    "        masks = tf.sign(tf.reduce_sum(tf.abs(keys), axis=-1))  # (N, T_k)\n",
    "        masks = tf.expand_dims(masks, 1) # (N, 1, T_k)\n",
    "        masks = tf.tile(masks, [1, tf.shape(queries)[1], 1])  # (N, T_q, T_k)\n",
    "        paddings = tf.ones_like(inputs) * padding_num\n",
    "        outputs = tf.where(tf.equal(masks, 0), paddings, inputs)  # (N, T_q, T_k)\n",
    "    elif type in (\"q\", \"query\", \"queries\"):\n",
    "        masks = tf.sign(tf.reduce_sum(tf.abs(queries), axis=-1))  # (N, T_q)\n",
    "        masks = tf.expand_dims(masks, -1)  # (N, T_q, 1)\n",
    "        masks = tf.tile(masks, [1, 1, tf.shape(keys)[1]])  # (N, T_q, T_k)\n",
    "        outputs = inputs*masks\n",
    "    elif type in (\"f\", \"future\", \"right\"):\n",
    "        diag_vals = tf.ones_like(inputs[0, :, :])  # (T_q, T_k)\n",
    "        tril = tf.linalg.LinearOperatorLowerTriangular(diag_vals).to_dense()  # (T_q, T_k)\n",
    "        masks = tf.tile(tf.expand_dims(tril, 0), [tf.shape(inputs)[0], 1, 1])  # (N, T_q, T_k)\n",
    "        paddings = tf.ones_like(masks) * padding_num\n",
    "        outputs = tf.where(tf.equal(masks, 0), paddings, inputs)\n",
    "    else:\n",
    "        print(\"Check if you entered type correctly!\")\n",
    "\n",
    "\n",
    "    return outputs\n",
    "\n",
    "def multihead_attention(queries, keys, values,\n",
    "                        num_heads=8, \n",
    "                        dropout_rate=0,\n",
    "                        training=True,\n",
    "                        causality=False,\n",
    "                        scope=\"multihead_attention\"):\n",
    "    d_model = queries.get_shape().as_list()[-1]\n",
    "    with tf.variable_scope(scope, reuse=tf.AUTO_REUSE):\n",
    "        # Linear projections\n",
    "        Q = tf.layers.dense(queries, d_model, use_bias=False) # (N, T_q, d_model)\n",
    "        K = tf.layers.dense(keys, d_model, use_bias=False) # (N, T_k, d_model)\n",
    "        V = tf.layers.dense(values, d_model, use_bias=False) # (N, T_k, d_model)\n",
    "        \n",
    "        Q_ = tf.concat(tf.split(Q, num_heads, axis=2), axis=0) # (h*N, T_q, d_model/h)\n",
    "        K_ = tf.concat(tf.split(K, num_heads, axis=2), axis=0) # (h*N, T_k, d_model/h)\n",
    "        V_ = tf.concat(tf.split(V, num_heads, axis=2), axis=0) # (h*N, T_k, d_model/h)\n",
    "\n",
    "        outputs = scaled_dot_product_attention(Q_, K_, V_, causality, dropout_rate, training)\n",
    "        outputs = tf.concat(tf.split(outputs, num_heads, axis=0), axis=2 ) # (N, T_q, d_model)\n",
    "        outputs += queries\n",
    "        outputs = ln(outputs)\n",
    " \n",
    "    return outputs\n",
    "\n",
    "def ff(inputs, num_units, scope=\"positionwise_feedforward\"):\n",
    "    with tf.variable_scope(scope, reuse=tf.AUTO_REUSE):\n",
    "        outputs = tf.layers.dense(inputs, num_units[0], activation=tf.nn.relu)\n",
    "        outputs = tf.layers.dense(outputs, num_units[1])\n",
    "        outputs += inputs\n",
    "        outputs = ln(outputs)\n",
    "    \n",
    "    return outputs\n",
    "\n",
    "def label_smoothing(inputs, epsilon=0.1):\n",
    "    V = inputs.get_shape().as_list()[-1] # number of channels\n",
    "    return ((1-epsilon) * inputs) + (epsilon / V)\n",
    "\n",
    "def sinusoidal_position_encoding(inputs, mask, repr_dim):\n",
    "    T = tf.shape(inputs)[1]\n",
    "    pos = tf.reshape(tf.range(0.0, tf.to_float(T), dtype=tf.float32), [-1, 1])\n",
    "    i = np.arange(0, repr_dim, 2, np.float32)\n",
    "    denom = np.reshape(np.power(10000.0, i / repr_dim), [1, -1])\n",
    "    enc = tf.expand_dims(tf.concat([tf.sin(pos / denom), tf.cos(pos / denom)], 1), 0)\n",
    "    return tf.tile(enc, [tf.shape(inputs)[0], 1, 1]) * tf.expand_dims(tf.to_float(mask), -1)\n",
    "\n",
    "class Translator:\n",
    "    def __init__(self, size_layer, learning_rate,\n",
    "                num_blocks = 4, num_heads = 8, ratio_hidden = 2, beam_width = 5):\n",
    "        \n",
    "        self.X = tf.placeholder(tf.int32, [None, None])\n",
    "        self.segment_ids = tf.placeholder(tf.int32, [None, None])\n",
    "        self.input_masks = tf.placeholder(tf.float32, [None, None])\n",
    "        self.Y = tf.placeholder(tf.int32, [None, None])\n",
    "        self.X_seq_len = tf.count_nonzero(self.X, 1, dtype=tf.int32)\n",
    "        self.Y_seq_len = tf.count_nonzero(self.Y, 1, dtype=tf.int32)\n",
    "        batch_size = tf.shape(self.X)[0]\n",
    "        \n",
    "        decoder_embedding = tf.Variable(tf.random_uniform([len(dictionary_to), size_layer], -1, 1))\n",
    "        \n",
    "        \n",
    "        def forward(x, segment, mask, y, reuse = False):\n",
    "            \n",
    "            with tf.variable_scope('xlnet',reuse=reuse):\n",
    "                xlnet_model = xlnet.XLNetModel(\n",
    "                    xlnet_config=xlnet_config,\n",
    "                    run_config=xlnet_parameters,\n",
    "                    input_ids=tf.transpose(x, [1, 0]),\n",
    "                    seg_ids=tf.transpose(segment, [1, 0]),\n",
    "                    input_mask=tf.transpose(mask, [1, 0]))\n",
    "                memory = xlnet_model.get_sequence_output()\n",
    "                memory = tf.transpose(memory, (1, 0, 2))\n",
    "            print(memory)\n",
    "            \n",
    "            decoder_embedded = tf.nn.embedding_lookup(decoder_embedding, y)\n",
    "            de_masks = tf.sign(y)\n",
    "            decoder_embedded += sinusoidal_position_encoding(y, de_masks, size_layer)\n",
    "            dec = decoder_embedded\n",
    "            \n",
    "            for i in range(num_blocks):\n",
    "                with tf.variable_scope('decoder_self_attn_%d'%i,reuse=reuse):\n",
    "                    dec = multihead_attention(queries=dec,\n",
    "                                              keys=dec,\n",
    "                                              values=dec,\n",
    "                                              num_heads=num_heads,\n",
    "                                              causality=True,\n",
    "                                              scope=\"self_attention\")\n",
    "\n",
    "                    dec = multihead_attention(queries=dec,\n",
    "                                              keys=memory,\n",
    "                                              values=memory,\n",
    "                                              num_heads=num_heads,\n",
    "                                              causality=False,\n",
    "                                              scope=\"vanilla_attention\")\n",
    "                    \n",
    "                    dec = ff(dec, num_units=[size_layer * ratio_hidden, size_layer])\n",
    "                \n",
    "            weights = tf.transpose(decoder_embedding)\n",
    "            logits = tf.einsum('ntd,dk->ntk', dec, weights)\n",
    "            return logits\n",
    "        \n",
    "        main = tf.strided_slice(self.Y, [0, 0], [batch_size, -1], [1, 1])\n",
    "        decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n",
    "        self.training_logits = forward(self.X, self.segment_ids, self.input_masks, decoder_input)\n",
    "\n",
    "        masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n",
    "        self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.training_logits,\n",
    "                                                     targets = self.Y,\n",
    "                                                     weights = masks)\n",
    "        self.optimizer, self.learning_rate, _ = model_utils.get_train_op(training_parameters, self.cost)\n",
    "        y_t = tf.argmax(self.training_logits,axis=2)\n",
    "        y_t = tf.cast(y_t, tf.int32)\n",
    "        self.prediction = tf.boolean_mask(y_t, masks)\n",
    "        mask_label = tf.boolean_mask(self.Y, masks)\n",
    "        correct_pred = tf.equal(self.prediction, mask_label)\n",
    "        correct_index = tf.cast(correct_pred, tf.float32)\n",
    "        self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))\n",
    "        \n",
    "        initial_ids = tf.fill([batch_size], GO)\n",
    "        \n",
    "        def symbols_to_logits(ids):\n",
    "            x = tf.contrib.seq2seq.tile_batch(self.X, beam_width)\n",
    "            segment = tf.contrib.seq2seq.tile_batch(self.segment_ids, beam_width)\n",
    "            masks = tf.contrib.seq2seq.tile_batch(self.input_masks, beam_width)\n",
    "            logits = forward(x, segment, masks, ids, reuse = True)\n",
    "            return logits[:, tf.shape(ids)[1]-1, :]\n",
    "        \n",
    "        final_ids, final_probs, _ = beam_search.beam_search(\n",
    "            symbols_to_logits,\n",
    "            initial_ids,\n",
    "            beam_width,\n",
    "            tf.reduce_max(self.X_seq_len),\n",
    "            size_vocab,\n",
    "            0.0,\n",
    "            eos_id = EOS)\n",
    "        \n",
    "        self.predicting_ids = final_ids"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "size_layer = 768\n",
    "learning_rate = 1e-5"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/util/deprecation.py:507: calling count_nonzero (from tensorflow.python.ops.math_ops) with axis is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "reduction_indices is deprecated, use axis instead\n",
      "WARNING:tensorflow:From /home/husein/english-vietnam/xlnet.py:220: The name tf.variable_scope is deprecated. Please use tf.compat.v1.variable_scope instead.\n",
      "\n",
      "WARNING:tensorflow:From /home/husein/english-vietnam/xlnet.py:220: The name tf.AUTO_REUSE is deprecated. Please use tf.compat.v1.AUTO_REUSE instead.\n",
      "\n",
      "WARNING:tensorflow:From /home/husein/english-vietnam/modeling.py:453: The name tf.logging.info is deprecated. Please use tf.compat.v1.logging.info instead.\n",
      "\n",
      "INFO:tensorflow:memory input None\n",
      "INFO:tensorflow:Use float type <dtype: 'float32'>\n",
      "WARNING:tensorflow:From /home/husein/english-vietnam/modeling.py:460: The name tf.get_variable is deprecated. Please use tf.compat.v1.get_variable instead.\n",
      "\n",
      "WARNING:tensorflow:From /home/husein/english-vietnam/modeling.py:535: dropout (from tensorflow.python.layers.core) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use keras.layers.dropout instead.\n",
      "WARNING:tensorflow:\n",
      "The TensorFlow contrib module will not be included in TensorFlow 2.0.\n",
      "For more information, please see:\n",
      "  * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md\n",
      "  * https://github.com/tensorflow/addons\n",
      "  * https://github.com/tensorflow/io (for I/O related ops)\n",
      "If you depend on functionality not listed there, please file an issue.\n",
      "\n",
      "WARNING:tensorflow:From /home/husein/english-vietnam/modeling.py:67: dense (from tensorflow.python.layers.core) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use keras.layers.dense instead.\n",
      "Tensor(\"xlnet/transpose_3:0\", shape=(?, ?, 768), dtype=float32)\n",
      "WARNING:tensorflow:From <ipython-input-12-6c364d2c84fb>:102: to_float (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use `tf.cast` instead.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/init_ops.py:1251: calling VarianceScaling.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Call initializer instance with the dtype argument instead of passing it to the constructor\n",
      "WARNING:tensorflow:From <ipython-input-12-6c364d2c84fb>:45: add_dispatch_support.<locals>.wrapper (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use tf.where in 2.0, which has the same broadcast rule as np.where\n",
      "WARNING:tensorflow:From /home/husein/english-vietnam/model_utils.py:96: The name tf.train.get_or_create_global_step is deprecated. Please use tf.compat.v1.train.get_or_create_global_step instead.\n",
      "\n",
      "WARNING:tensorflow:From /home/husein/english-vietnam/model_utils.py:108: The name tf.train.polynomial_decay is deprecated. Please use tf.compat.v1.train.polynomial_decay instead.\n",
      "\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/keras/optimizer_v2/learning_rate_schedule.py:409: div (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Deprecated in favor of operator or tf.math.divide.\n",
      "WARNING:tensorflow:From /home/husein/english-vietnam/model_utils.py:131: The name tf.train.AdamOptimizer is deprecated. Please use tf.compat.v1.train.AdamOptimizer instead.\n",
      "\n",
      "INFO:tensorflow:memory input None\n",
      "INFO:tensorflow:Use float type <dtype: 'float32'>\n",
      "Tensor(\"while/xlnet/transpose_3:0\", shape=(?, ?, 768), dtype=float32)\n"
     ]
    }
   ],
   "source": [
    "tf.reset_default_graph()\n",
    "sess = tf.InteractiveSession()\n",
    "model = Translator(size_layer, learning_rate)\n",
    "sess.run(tf.global_variables_initializer())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "import collections\n",
    "import re\n",
    "\n",
    "def get_assignment_map_from_checkpoint(tvars, init_checkpoint):\n",
    "    \"\"\"Compute the union of the current variables and checkpoint variables.\"\"\"\n",
    "    assignment_map = {}\n",
    "    initialized_variable_names = {}\n",
    "\n",
    "    name_to_variable = collections.OrderedDict()\n",
    "    for var in tvars:\n",
    "        name = var.name\n",
    "        m = re.match('^(.*):\\\\d+$', name)\n",
    "        if m is not None:\n",
    "            name = m.group(1)\n",
    "        name_to_variable[name] = var\n",
    "\n",
    "    init_vars = tf.train.list_variables(init_checkpoint)\n",
    "\n",
    "    assignment_map = collections.OrderedDict()\n",
    "    for x in init_vars:\n",
    "        (name, var) = (x[0], x[1])\n",
    "        if 'xlnet/' + name not in name_to_variable:\n",
    "            continue\n",
    "        assignment_map[name] = name_to_variable['xlnet/' + name]\n",
    "        initialized_variable_names[name] = 1\n",
    "        initialized_variable_names[name + ':0'] = 1\n",
    "\n",
    "    return (assignment_map, initialized_variable_names)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    "tvars = tf.trainable_variables()\n",
    "\n",
    "checkpoint = 'xlnet_cased_L-12_H-768_A-12/xlnet_model.ckpt'\n",
    "assignment_map, initialized_variable_names = get_assignment_map_from_checkpoint(tvars, \n",
    "                                                                                checkpoint)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/training/saver.py:1276: checkpoint_exists (from tensorflow.python.training.checkpoint_management) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use standard file APIs to check for files with this prefix.\n",
      "INFO:tensorflow:Restoring parameters from xlnet_cased_L-12_H-768_A-12/xlnet_model.ckpt\n"
     ]
    }
   ],
   "source": [
    "saver = tf.train.Saver(var_list = assignment_map)\n",
    "saver.restore(sess, checkpoint)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [],
   "source": [
    "def str_idx(corpus, dic):\n",
    "    X = []\n",
    "    for i in corpus:\n",
    "        ints = []\n",
    "        for k in i.split():\n",
    "            ints.append(dic.get(k,UNK))\n",
    "        X.append(ints)\n",
    "    return X\n",
    "\n",
    "def pad_sentence_batch(sentence_batch, pad_int):\n",
    "    padded_seqs = []\n",
    "    seq_lens = []\n",
    "    max_sentence_len = max([len(sentence) for sentence in sentence_batch])\n",
    "    for sentence in sentence_batch:\n",
    "        padded_seqs.append(sentence + [pad_int] * (max_sentence_len - len(sentence)))\n",
    "        seq_lens.append(len(sentence))\n",
    "    return padded_seqs, seq_lens"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_Y = str_idx(train_Y, dictionary_to)\n",
    "test_Y = str_idx(test_Y, dictionary_to)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [],
   "source": [
    "# train_input_ids, train_input_masks, train_segment_ids\n",
    "# test_input_ids, test_input_masks, test_segment_ids\n",
    "# self.X = tf.placeholder(tf.int32, [None, None])\n",
    "# self.segment_ids = tf.placeholder(tf.int32, [None, None])\n",
    "# self.input_masks = tf.placeholder(tf.float32, [None, None])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(133259, 133259, 133259, 133259)"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "len(train_input_ids), len(train_segment_ids), len(train_input_masks), len(train_Y)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(2821, 2821, 2821, 2821)"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "len(test_input_ids), len(test_segment_ids), len(test_input_masks), len(test_Y)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[69.729965, 0.0]"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "sess.run([model.cost, model.accuracy], feed_dict = {model.X: [train_input_ids[0]],\n",
    "                                            model.segment_ids: [train_segment_ids[0]],\n",
    "                                            model.input_masks: [train_input_masks[0]],\n",
    "                                            model.Y: [train_Y[0]]})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 4165/4165 [25:33<00:00,  2.72it/s, accuracy=0.0793, cost=13.9] \n",
      "minibatch loop: 100%|██████████| 89/89 [00:10<00:00,  8.18it/s, accuracy=0.096, cost=12.7] \n",
      "minibatch loop:   0%|          | 0/4165 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 1, training avg loss 21.692877, training avg acc 0.047738\n",
      "epoch 1, testing avg loss 12.675898, testing avg acc 0.083630\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 4165/4165 [25:24<00:00,  2.73it/s, accuracy=0.141, cost=8.01] \n",
      "minibatch loop: 100%|██████████| 89/89 [00:10<00:00,  8.19it/s, accuracy=0.169, cost=7.82]\n",
      "minibatch loop:   0%|          | 0/4165 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 2, training avg loss 9.337718, training avg acc 0.128022\n",
      "epoch 2, testing avg loss 7.195321, testing avg acc 0.169290\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 4165/4165 [25:23<00:00,  2.73it/s, accuracy=0.179, cost=6.2] \n",
      "minibatch loop: 100%|██████████| 89/89 [00:10<00:00,  8.20it/s, accuracy=0.203, cost=6.12]\n",
      "minibatch loop:   0%|          | 0/4165 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 3, training avg loss 6.143311, training avg acc 0.214900\n",
      "epoch 3, testing avg loss 5.739505, testing avg acc 0.212040\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 4165/4165 [25:24<00:00,  2.73it/s, accuracy=0.21, cost=5.5]  \n",
      "minibatch loop: 100%|██████████| 89/89 [00:10<00:00,  8.17it/s, accuracy=0.232, cost=5.55]\n",
      "minibatch loop:   0%|          | 0/4165 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 4, training avg loss 5.164574, training avg acc 0.264736\n",
      "epoch 4, testing avg loss 5.216041, testing avg acc 0.231996\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 4165/4165 [25:25<00:00,  2.73it/s, accuracy=0.241, cost=5.05]\n",
      "minibatch loop: 100%|██████████| 89/89 [00:10<00:00,  8.17it/s, accuracy=0.26, cost=5.11] \n",
      "minibatch loop:   0%|          | 0/4165 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 5, training avg loss 4.676654, training avg acc 0.295971\n",
      "epoch 5, testing avg loss 4.794361, testing avg acc 0.270686\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 4165/4165 [25:25<00:00,  2.73it/s, accuracy=0.262, cost=4.73]\n",
      "minibatch loop: 100%|██████████| 89/89 [00:10<00:00,  8.21it/s, accuracy=0.266, cost=4.92]\n",
      "minibatch loop:   0%|          | 0/4165 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 6, training avg loss 4.348268, training avg acc 0.320956\n",
      "epoch 6, testing avg loss 4.603140, testing avg acc 0.287897\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 4165/4165 [25:25<00:00,  2.73it/s, accuracy=0.324, cost=4.42]\n",
      "minibatch loop: 100%|██████████| 89/89 [00:10<00:00,  8.19it/s, accuracy=0.254, cost=4.83]\n",
      "minibatch loop:   0%|          | 0/4165 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 7, training avg loss 4.095811, training avg acc 0.342908\n",
      "epoch 7, testing avg loss 4.526076, testing avg acc 0.292742\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 4165/4165 [25:37<00:00,  2.71it/s, accuracy=0.359, cost=4.12]\n",
      "minibatch loop: 100%|██████████| 89/89 [00:10<00:00,  8.20it/s, accuracy=0.249, cost=4.77]\n",
      "minibatch loop:   0%|          | 0/4165 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 8, training avg loss 3.883485, training avg acc 0.363184\n",
      "epoch 8, testing avg loss 4.498834, testing avg acc 0.294282\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 4165/4165 [25:25<00:00,  2.73it/s, accuracy=0.397, cost=3.83]\n",
      "minibatch loop: 100%|██████████| 89/89 [00:10<00:00,  8.22it/s, accuracy=0.243, cost=4.73]\n",
      "minibatch loop:   0%|          | 0/4165 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 9, training avg loss 3.693927, training avg acc 0.383235\n",
      "epoch 9, testing avg loss 4.486375, testing avg acc 0.296450\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 4165/4165 [25:25<00:00,  2.73it/s, accuracy=0.417, cost=3.54]\n",
      "minibatch loop: 100%|██████████| 89/89 [00:10<00:00,  8.19it/s, accuracy=0.226, cost=4.71]\n",
      "minibatch loop:   0%|          | 0/4165 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 10, training avg loss 3.518262, training avg acc 0.403752\n",
      "epoch 10, testing avg loss 4.522978, testing avg acc 0.297018\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 4165/4165 [25:25<00:00,  2.73it/s, accuracy=0.434, cost=3.28]\n",
      "minibatch loop: 100%|██████████| 89/89 [00:10<00:00,  8.20it/s, accuracy=0.237, cost=4.74]\n",
      "minibatch loop:   0%|          | 0/4165 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 11, training avg loss 3.354566, training avg acc 0.423882\n",
      "epoch 11, testing avg loss 4.623637, testing avg acc 0.293335\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 4165/4165 [25:25<00:00,  2.73it/s, accuracy=0.483, cost=3.05]\n",
      "minibatch loop: 100%|██████████| 89/89 [00:10<00:00,  8.15it/s, accuracy=0.237, cost=4.76]\n",
      "minibatch loop:   0%|          | 0/4165 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 12, training avg loss 3.202179, training avg acc 0.443475\n",
      "epoch 12, testing avg loss 4.733461, testing avg acc 0.286778\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 4165/4165 [25:25<00:00,  2.73it/s, accuracy=0.531, cost=2.85]\n",
      "minibatch loop: 100%|██████████| 89/89 [00:10<00:00,  8.22it/s, accuracy=0.249, cost=4.78]\n",
      "minibatch loop:   0%|          | 0/4165 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 13, training avg loss 3.061537, training avg acc 0.462180\n",
      "epoch 13, testing avg loss 4.819852, testing avg acc 0.283115\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 4165/4165 [25:23<00:00,  2.73it/s, accuracy=0.559, cost=2.68] \n",
      "minibatch loop: 100%|██████████| 89/89 [00:10<00:00,  8.17it/s, accuracy=0.249, cost=4.84]\n",
      "minibatch loop:   0%|          | 0/4165 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 14, training avg loss 2.933535, training avg acc 0.479504\n",
      "epoch 14, testing avg loss 4.938883, testing avg acc 0.278135\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 4165/4165 [25:24<00:00,  2.73it/s, accuracy=0.559, cost=2.53] \n",
      "minibatch loop: 100%|██████████| 89/89 [00:10<00:00,  8.22it/s, accuracy=0.237, cost=4.93]\n",
      "minibatch loop:   0%|          | 0/4165 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 15, training avg loss 2.818423, training avg acc 0.495691\n",
      "epoch 15, testing avg loss 5.102652, testing avg acc 0.272984\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 4165/4165 [25:22<00:00,  2.73it/s, accuracy=0.59, cost=2.42]  \n",
      "minibatch loop: 100%|██████████| 89/89 [00:10<00:00,  8.22it/s, accuracy=0.254, cost=5.04]\n",
      "minibatch loop:   0%|          | 0/4165 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 16, training avg loss 2.718724, training avg acc 0.509931\n",
      "epoch 16, testing avg loss 5.265281, testing avg acc 0.272901\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 4165/4165 [25:22<00:00,  2.74it/s, accuracy=0.576, cost=2.35] \n",
      "minibatch loop: 100%|██████████| 89/89 [00:10<00:00,  8.21it/s, accuracy=0.243, cost=5.15]\n",
      "minibatch loop:   0%|          | 0/4165 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 17, training avg loss 2.636617, training avg acc 0.522048\n",
      "epoch 17, testing avg loss 5.476555, testing avg acc 0.269884\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 4165/4165 [25:22<00:00,  2.74it/s, accuracy=0.576, cost=2.32] \n",
      "minibatch loop: 100%|██████████| 89/89 [00:10<00:00,  8.22it/s, accuracy=0.237, cost=5.17]\n",
      "minibatch loop:   0%|          | 0/4165 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 18, training avg loss 2.577286, training avg acc 0.530053\n",
      "epoch 18, testing avg loss 5.566386, testing avg acc 0.269047\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 4165/4165 [25:21<00:00,  2.74it/s, accuracy=0.583, cost=2.33] \n",
      "minibatch loop: 100%|██████████| 89/89 [00:10<00:00,  8.20it/s, accuracy=0.266, cost=5.08]\n",
      "minibatch loop:   0%|          | 0/4165 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 19, training avg loss 2.554250, training avg acc 0.530188\n",
      "epoch 19, testing avg loss 5.461653, testing avg acc 0.274765\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 4165/4165 [25:22<00:00,  2.73it/s, accuracy=0.538, cost=2.52] \n",
      "minibatch loop: 100%|██████████| 89/89 [00:11<00:00,  7.84it/s, accuracy=0.249, cost=4.89]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 20, training avg loss 2.601457, training avg acc 0.515407\n",
      "epoch 20, testing avg loss 5.154055, testing avg acc 0.288339\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "import tqdm\n",
    "\n",
    "for e in range(epoch):\n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(train_input_ids), batch_size), desc = 'minibatch loop')\n",
    "    train_loss, train_acc, test_loss, test_acc = [], [], [], []\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(train_input_ids))\n",
    "        batch_x, _ = pad_sentence_batch(train_input_ids[i : index], PAD)\n",
    "        batch_masks, _ = pad_sentence_batch(train_input_masks[i : index], 1)\n",
    "        batch_segment, _ = pad_sentence_batch(train_segment_ids[i : index], SEG_ID_PAD)\n",
    "        batch_y, seq_y = pad_sentence_batch(train_Y[i : index], PAD)\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y,\n",
    "                model.input_masks: batch_masks,\n",
    "                model.segment_ids: batch_segment}\n",
    "        accuracy, loss, _ = sess.run([model.accuracy,model.cost,model.optimizer],\n",
    "                                    feed_dict = feed)\n",
    "        train_loss.append(loss)\n",
    "        train_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(test_input_ids), batch_size), desc = 'minibatch loop')\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(test_input_ids))\n",
    "        batch_x, _ = pad_sentence_batch(test_input_ids[i : index], PAD)\n",
    "        batch_masks, _ = pad_sentence_batch(test_input_masks[i : index], 1)\n",
    "        batch_segment, _ = pad_sentence_batch(test_segment_ids[i : index], SEG_ID_PAD)\n",
    "        batch_y, seq_y = pad_sentence_batch(test_Y[i : index], PAD)\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y,\n",
    "                model.input_masks: batch_masks,\n",
    "                model.segment_ids: batch_segment}\n",
    "        accuracy, loss = sess.run([model.accuracy,model.cost],\n",
    "                                    feed_dict = feed)\n",
    "\n",
    "        test_loss.append(loss)\n",
    "        test_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    print('epoch %d, training avg loss %f, training avg acc %f'%(e+1,\n",
    "                                                                 np.mean(train_loss),np.mean(train_acc)))\n",
    "    print('epoch %d, testing avg loss %f, testing avg acc %f'%(e+1,\n",
    "                                                              np.mean(test_loss),np.mean(test_acc)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
